<!--
 * @Description:
 * @Author: william
 * @Date: 2025-02-17 16:47:40
 * @LastEditors: william
 * @LastEditTime: 2025-05-20 15:42:57
-->
<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    style="width: 850px"
    width="850px"
    :before-close="handleClose"
  >
    <BaseTravel ref="refChildForm" :type="props.type" :row="props.row" />
    <el-form
      ref="refDialogForm"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('fleet.travelDistance')" prop="kilometres">
            <TextInput
              v-model="formData.kilometres"
              :label="$t('fleet.travelDistance')"
              verify-type="float"
              @blur="handleInputBlur('kilometres')"
            >
              <template #suffix>{{ $t('fleet.kilometer') }}</template>
            </TextInput>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('fleet.passingScenery')" prop="through">
            <TextInput
              v-model="formData.through"
              type="textarea"
              :maxlength="512"
              :rows="4"
              :label="$t('fleet.passingScenery')"
            >
              <template #suffix>{{ $t('fleet.kilometer') }}</template>
            </TextInput>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>
</template>

<script setup>
const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  row: {
    type: Object,
    default: () => {}
  }
})

const emit = defineEmits(['add', 'update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() =>
  props.type === 'add' ? g_t('fleet.addTrip') : g_t('fleet.editTrip')
)

const refChildForm = ref(null)
const refDialogForm = ref(null)
const formData = ref({
  kilometres: '',
  through: ''
})
const rules = {
  kilometres: g_rules.travelDistance({
    required: false
  })
}

// // 初始化地图（不需要显示地图时可不传container）
// function getLocation() {
//   console.log('AMap.plugin', AMap.plugin)
//   AMap.plugin('AMap.Geolocation', () => {
//     const geolocation = new AMap.Geolocation({
//       enableHighAccuracy: true, // 高精度定位
//       timeout: 3000 // 超时时间（毫秒）
//     })

//     // 获取当前位置
//     geolocation.getCurrentPosition((status, result) => {
//       if (status === 'complete') {
//         console.log('定位成功:', result)
//         const address = result.formattedAddress // 完整地址
//         const city = result.addressComponent.city // 城市
//         alert(`您的位置：${address}`)
//       } else {
//         console.error('定位失败:', result)
//         console.log('无法获取位置，请确保已授权地理位置权限')
//       }
//     })
//   })
// }

onMounted(async () => {
  // 调用
  // getLocation()
  if (props.type === 'edit') {
    g_utils.assignFormData(formData.value, props.row)
    props.row.id && (formData.value.id = props.row.id)
    console.log('parentForm.value', formData.value)
  }
})

const handleClose = _ => {
  dialogVisible.value = false
}

const handleInputBlur = prop => {
  // 数字化处理
  refDialogForm.value.validateField([prop], vaild => {
    if (vaild && formData.value[prop]) {
      formData.value[prop] = formData.value[prop] * 1
    }
  })
}

const handleSubmitForm = () => {
  const newFormData = {
    ...refChildForm.value.formData,
    ...formData.value
  }
  console.log('newFormData', newFormData)
  Promise.all([
    refChildForm.value.refDialogForm.validate(),
    refDialogForm.value.validate()
  ])
    .then(() => {
      console.log('所有表单验证通过')
      // 都没填写不需要保存
      const valid2 = Object.keys(newFormData).some(k => {
        return newFormData[k].length
      })
      handleClose()
      valid2 && emit(props.type === 'add' ? 'add' : 'update', newFormData)
    })
    .catch(() => {
      console.log('有表单验证未通过')
    })
}
</script>

<style scoped lang="scss"></style>
